layui.define(['setter', 'layer', 'form', 'upload', 'AppHelper', 'routerHelper', 'auth'], function (experts) {
        var $ = layui.$,
            layer = layui.layer,
            form = layui.form,
            upload = layui.upload,
            routerHelper = layui.routerHelper,
            AppHelper = layui.AppHelper,
            baseUri = "/api/organization/ebook",
            setter = layui.setter;

        function EbookParser(params) {
            var that = this;
            this.swiper = null;
            this.defaultParams = {
                iframeUrl: ""
                , data: null
                , success: function (that) {

                }
            }


            this.config = $.extend({}, this.defaultParams, params);

            this.formData = null;

            this.iframe = $("#previewBox");

            //加载远程模板页面
            var editParams = "showPage=false&noSwiping=true";
            this.iframe.attr("src", that.combineUrl(editParams));


            //加载成功回调
            this.iframe[0].onload = function () {
                that.swiper = that.iframe[0].contentWindow.swiper;

                if (that.config.data) {
                    that.formData = that.config.data;
                    //渲染模板
                    $.each(that.formData.pages, function (index, item) {
                        that.renderTemplate(index);
                    })
                } else {
                    that.formData = that.parseData();
                }

                //初始化page
                var html = juicer("#pageTmp", {
                    count: that.formData.pageCount
                    , active: 0   //当前激活页数
                });
                $("#ebookPage").html(html);

                //绑定切换页面事件
                var pageItems = $("#ebookPage").find(".ebook-page-item");
                var pageMarks = $("#ebookPage").find(".ebook-page-mark");
                pageItems.each(function (index, item) {
                    $(this).on("click", function () {
                        //设置高亮
                        var activeClz = "layui-bg-orange";
                        pageItems.removeClass(activeClz);
                        $(this).addClass(activeClz);

                        //未选中则置灰色
                        var grayClz = "layui-bg-gray";
                        pageMarks.addClass(grayClz);
                        $(this).find(".ebook-page-mark").removeClass(grayClz);

                        that.toPage(index);

                        //渲染表单
                        that.renderForm(index);
                    })
                });

                //渲染默认表单
                that.renderForm(0);


                //执行成功回调
                that.config.success(that);
            }


        }

        EbookParser.prototype.renderTemplate = function (pageNum) {
            var that = this;
            var pageData = that.formData.pages[pageNum];
            $.each(pageData, function (index, item) {
                var type = item.type;
                switch (type) {
                    case "img":
                        that.setVal(item.name, item.val);
                        break;
                    default :
                        that.setVal(item.name, item.val);
                        break;
                }
            })
        }

        EbookParser.prototype.renderForm = function (pageNum) {
            var that = this;
            var pageData = that.formData.pages[pageNum];
            var formHtml = juicer("#formDataTmp", {items: pageData})
            $("#formData").html(formHtml);

            //绑定事件
            var tmpWrap = $("#formData");
            $.each(pageData, function (index, item) {
                var type = item.type;
                var currentVal = null;
                switch (type) {
                    case "img":
                        var elem = item.name + "Upload";
                        var elemUrl = item.name + "Url";
                        upload.render({
                            elem: "#" + elem
                            , url: setter.apiHost + "/api/aliy/oss/upload"
                            , data: {
                                type: "IMG"
                            }
                            , accept: "images"
                            , acceptMime: "image/*"
                            , done: function (res, uploadIndex, upload) {
                                console.log(res)
                                currentVal = res.data.publicUrl;
                                $("#" + elemUrl).val(currentVal);
                                that.setVal(item.name, currentVal);
                                //修改内存中的值
                                that.formData.pages[pageNum][index].val = currentVal;
                            }
                        })
                        break;
                    default :
                        tmpWrap.find("[name='" + item.name + "']").on("keyup", function () {
                            currentVal = $(this).val();
                            that.setVal(item.name, currentVal);
                            //修改内存中的值
                            that.formData.pages[pageNum][index].val = currentVal;
                        })
                        break;
                }
            })
        }

        EbookParser.prototype.parseData = function () {
            var that = this;
            var formData = {
                pageCount: 0
                , pages: []
            }
            //获取页数
            var sections = that.iframe.contents().find("section");
            formData.pageCount = sections.length;

            //获取每页表单
            $.each(sections, function (index, item) {
                //查找表单项
                var formItems = $(this).find("[data-mark]");
                var pageFormItems = [];
                $.each(formItems, function (itemIndex, formItem) {
                    var pageFormItem = {
                        alias: $(formItem).data("mark")
                        , name: $(formItem).data("mark-name")
                        , type: $(formItem).data("mark-type")
                        , pageNum: $(formItem).data("mark-page")
                        , val: ""
                    }

                    switch (pageFormItem.type) {
                        case "img":
                            pageFormItem.val = $(formItem).attr("src");
                            break;
                        default :
                            pageFormItem.val = $(formItem).text();
                            break;
                    }

                    pageFormItems.push(pageFormItem);
                })

                formData.pages.push(pageFormItems);
            })
            return formData;
        }

        EbookParser.prototype.toPage = function (pageNum) {
            this.swiper.slideTo(pageNum);
        }

        EbookParser.prototype.find = function (name) {
            var that = this;
            var target = that.iframe.contents().find("[data-mark-name='" + name + "']");
            return target;
        }

        EbookParser.prototype.setVal = function (name, val) {
            var that = this;
            that.setIframeVal(that.iframe, name, val);
        }

        EbookParser.prototype.setIframeVal = function (iframe, name, val) {
            var target = iframe.contents().find("[data-mark-name='" + name + "']");
            // console.log("target:", target)
            var type = target.data("mark-type");
            switch (type) {
                case "img":
                    target.attr("src", val);
                    break;
                default :
                    target.text(val);
                    break;
            }
        }

        EbookParser.prototype.combineUrl = function (params) {
            var that = this;
            var iframeUrl = that.config.iframeUrl;
            if (iframeUrl.lastIndexOf("?") > 0) {
                return iframeUrl + "&" + params;
            } else {

                return iframeUrl + "?" + params;
            }
        }

        EbookParser.prototype.recoverData = function (iframe) {
            var that = this;
            $.each(that.formData.pages, function (index, pageData) {
                $.each(pageData, function (itemIndex, item) {
                    that.setIframeVal(iframe, item.name, item.val);
                })
            });
        }

        EbookParser.prototype.preview = function () {
            var that = this;
            var topW = AppHelper.getTopWindow();
            var previewParams = "showPage=true&noSwiping=false"
            topW.layui.layer.open({
                type: 2
                , title: "预览电子画册"
                , content: that.combineUrl(previewParams)
                , area: ['375px', '667px']
                , success: function (layero, index) {
                    that.recoverData(layero.find('iframe'));
                }
            })
        }

        EbookParser.prototype.getData = function () {
            return this.formData;
        }

        EbookParser.prototype.getDataToJson = function () {
            return JSON.stringify(this.formData);
        }


        experts("ebook", {
            request: {

                getTemplates: function () {
                    return $.ajax({
                        url: setter.apiHost + baseUri + "/template"
                        , type: "GET"
                    })
                },
                getTemplateById: function (id) {
                    return $.ajax({
                        url: setter.apiHost + baseUri + "/template/" + id
                        , type: "GET"
                    })
                },
                saveEbook: function (ebook) {
                    return $.ajax({
                        url: setter.apiHost + baseUri
                        , type: "POST"
                        , contentType: "application/json"
                        , data: JSON.stringify(ebook)
                    })
                },
                updateEbookData: function (id, data) {
                    return $.ajax({
                        url: setter.apiHost + baseUri + "/" + id
                        , type: "PUT"
                        , contentType: "application/json"
                        , data: JSON.stringify({data: data})
                    })
                },
                getEbook: function (id) {
                    return $.ajax({
                        url: setter.apiHost + baseUri + "/" + id
                        , type: "GET"
                    })
                },
                deployEbook: function (id) {
                    return $.ajax({
                        url: setter.apiHost + baseUri + "/deploy/" + id
                        , type: "PUT"
                    })
                },
                cancelDeployEbook: function (id) {
                    return $.ajax({
                        url: setter.apiHost + baseUri + "/cancel_deploy/" + id
                        , type: "PUT"
                    })
                },
                delEbook: function (id) {
                    return $.ajax({
                        url: setter.apiHost + baseUri + "/" + id
                        , type: "DELETE"
                    })
                },
                page: function () {
                    return $.ajax({
                        url: setter.apiHost + baseUri + "/page"
                        , type: "GET"
                    })
                }
            }
            , action: {
                openEdit: function (ebookId, templateId) {
                    var pagePath = routerHelper.jump({
                        path: "./ebook/ebook_draw.html"
                        , query: {
                            id: ebookId
                            , templateId: templateId
                        }
                    })

                    var topWindow = AppHelper.getTopWindow();
                    topWindow.layui.layer.open({
                        type: 2,
                        title: false,
                        closeBtn: 0,
                        content: pagePath,
                        area: ['100%', '100%'],
                        success: function (layero, index) {
                            topWindow.layui.layer.full(index);
                        },
                        end: function(){
                           layui.table.reload("ebook-list");
                        }
                    })
                }
            }
            , init: function (params) {
                new EbookParser(params);
            }
        })
    }
)